package com.magicsoft.weitown.fragment;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;

import com.boyuan.huijiaoyu.Html5_Activity;
import com.boyuan.huijiaoyu.R;
import com.example.app.AppJson;
import com.magicsoft.app.adapter.HomeMenuListAdapter;
import com.magicsoft.app.entity.EmployeeRightsEntity;
import com.magicsoft.app.helper.DateUtils;
import com.magicsoft.app.helper.SharePreferenceHelper;
import com.magicsoft.app.helper.StringUtils;
import com.magicsoft.app.helper.ToastHelper;
import com.magicsoft.app.wcf.HomeService;
import com.magicsoft.app.wcf.listener.GetOneRecordListener;
import com.magicsoft.constant.Constant;
import com.magicsoft.weitown.ui.ThirdAppInstallDialog;
import com.magicsoft.weitown.ui.ThirdAppInstallDialog.ThirdAppInstallListener;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.ttcaca.cas.android.client.model.User;

/**
 * 应用
 * 
 * @author
 * 
 */
public class HomeAppFragment extends BaseFragment implements OnClickListener {
	private final static String TAG = "HomeAppFragment";
	private HomeMenuListAdapter homeMenuListAdapter;
	private ListView listView;
	private HomeService homeService;
	private DisplayImageOptions options;
	private ThirdAppInstallDialog appInstallDialog;
	private ThirdAppInstallListener appInstallListener;
	private ArrayList<EmployeeRightsEntity> homeMenuDatas = new ArrayList<EmployeeRightsEntity>();
	private ArrayList<EmployeeRightsEntity> AllMenuDatas = new ArrayList<EmployeeRightsEntity>();
	private User account;
	HashMap<String, Boolean> isShowManage = new HashMap<String, Boolean>();
	private boolean isJumpOutOfAppSharing = false;

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View view = inflater.inflate(R.layout.home_app_fragment, null);
		options = new DisplayImageOptions.Builder()
				.showImageOnLoading(R.drawable.placeholder2)
				.showImageForEmptyUri(R.drawable.placeholder2)
				.showImageOnFail(R.drawable.placeholder2).cacheInMemory(true)
				.cacheOnDisc(true).considerExifParams(true)
				// .displayer(new RoundedBitmapDisplayer(20))
				.build();
		homeMenuListAdapter = new HomeMenuListAdapter(getActivity(),
				homeMenuDatas, options, imageLoader);

		view.findViewById(R.id.tv_manage).setOnClickListener(this);
		listView = (ListView) view.findViewById(R.id.listView1);
		listView.setAdapter(homeMenuListAdapter);
		listView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				// TODO Auto-generated method stub
				Log.i(TAG, "position = " + arg2);
				EmployeeRightsEntity employeeRightsEntity = homeMenuDatas
						.get(arg2);
				String name = employeeRightsEntity.getName();
				String type = employeeRightsEntity.getType();

				if ("native".equals(type)) {

					if ("云端学习".endsWith(name)) {

						String url = "";
						if (isAvilible(getActivity(),
								"com.tbc.android.defaults")) {
							url = employeeRightsEntity.getUrl().getNormal();

							Log.i(TAG, url);

							Intent shiDaiGuangHuaIntent = getActivity()
									.getPackageManager()
									.getLaunchIntentForPackage(
											"com.tbc.android.defaults");
							int temp = url.indexOf("?");

							url = url.substring(temp + 1, url.length());
							Log.i(TAG, url);
							String[] arr2 = url.split("&");
							for (int i = 0; i < arr2.length; i++) {
								String[] arr3 = arr2[i].split("=");
								Log.i(TAG, arr3[0] + " = " + arr3[1]);
								if ("action".equals(arr3[0])) {
									shiDaiGuangHuaIntent.setAction(arr3[1]);
								} else {
									shiDaiGuangHuaIntent.putExtra(arr3[0],
											arr3[1]);
								}
							}

							startActivity(shiDaiGuangHuaIntent);
							isJumpOutOfAppSharing = true;

						} else {
							url = employeeRightsEntity.getUrl().getAndroid();
							showInstallDialog(url);
						}
					}
				} else if ("html5".equals(type)) {

					String url = "";
					if (StringUtils.isNotEmpty(employeeRightsEntity.getUrl()
							.getNormal())) {
						url = employeeRightsEntity.getUrl().getNormal();
					} else {
						// name,
						// employeeRightsEntity.getUrl().getSso(),employeeRightsEntity.getClientCode()
						getAuth();

						return;
					}

					Intent intent = new Intent(getActivity(),
							Html5_Activity.class);
					intent.putExtra("title", name);
					intent.putExtra("addr", url);
					intent.putExtra("isloading", 0);
					intent.putExtra("father_level", "应用");
					startActivity(intent);

				}

			}
		});
		getEmployeeRight();
		// getAuth();
		return view;
	}

	private void showInstallDialog(final String url) {

		if (appInstallDialog == null) {
			appInstallDialog = new ThirdAppInstallDialog(getActivity(),
					R.style.qr_dialog);
			// http://v4.21tb.com/CloudStudy.apk
			if (appInstallListener == null) {
				appInstallListener = new ThirdAppInstallListener() {

					@Override
					public void positive() {

						appInstallDialog.dismiss();

						Uri uri = Uri.parse(url);

						Intent intent = new Intent(Intent.ACTION_VIEW, uri);

						startActivity(intent);
					}

					@Override
					public void negative() {
						appInstallDialog.dismiss();
					}
				};
			}

			appInstallDialog.setThirdAppInstallListener(appInstallListener);
		}

		appInstallDialog.show();
	}

	public static boolean isAvilible(Context context, String packageName) {
		// 获取packagemanager
		final PackageManager packageManager = context.getPackageManager();
		// 获取所有已安装程序的包信息
		List<PackageInfo> packageInfos = packageManager.getInstalledPackages(0);
		// 用于存储所有已安装程序的包名
		List<String> packageNames = new ArrayList<String>();
		// 从pinfo中将包名字逐一取出，压入pName list中
		if (packageInfos != null) {
			for (int i = 0; i < packageInfos.size(); i++) {
				String packName = packageInfos.get(i).packageName;
				packageNames.add(packName);
			}
		}
		// 判断packageNames中是否有目标程序的包名，有TRUE，没有FALSE
		return packageNames.contains(packageName);
	}

	// final String name, final String url, String clientCode
	private void getAuth() {
		if (homeService == null) {
			homeService = new HomeService(getActivity());
		}

		homeService
				.getAuth(new GetOneRecordListener<List<EmployeeRightsEntity>>() {

					@Override
					public void onFinish(
							List<EmployeeRightsEntity> employeeResps) {
						// TODO Auto-generated method stub
						// Intent intent = new Intent(getActivity(),
						// Html5_Activity.class);
						// intent.putExtra("title", name);
						// intent.putExtra("addr", url + "?openID=" + openID
						// + "&accessToken=" + accessToken);
						// intent.putExtra("isloading", 0);
						// startActivity(intent);
						if (employeeResps != null) {
							homeMenuDatas.addAll(employeeResps);
						}
						homeMenuListAdapter.notifyDataSetChanged();
					}

					@Override
					public void onFailed(String Message) {
						// TODO Auto-generated method stub
						ToastHelper.showMsg(getActivity(), Message, false);
					}
				});
	}

	// 获取本地缓存数据
	private void getCacheEmployee() {
		homeMenuDatas.clear();
		// AllMenuDatas.clear();

		ArrayList<EmployeeRightsEntity> list = SharePreferenceHelper
				.getAppList(getActivity());

		if (list != null) {
			homeMenuDatas.addAll(list);
			// AllMenuDatas.addAll(list);
			homeMenuListAdapter.notifyDataSetChanged();
		}

	}

	private void getEmployeeRight() {
		if (homeService == null) {
			homeService = new HomeService(getActivity());
		}

		homeService
				.getEmployeeRight(new GetOneRecordListener<List<EmployeeRightsEntity>>() {
					@Override
					public void onFinish(List<EmployeeRightsEntity> data) {
						// TODO Auto-generated method stub
						// Log.e(TAG, "onFinish:" + homeMenuDatas.size());
						// TODO Auto-generated method stub
						homeMenuDatas.clear();
						AllMenuDatas.clear();

						if (data != null) {
							homeMenuDatas.addAll(data);
							AllMenuDatas.addAll(data);

						}
						initIsShow();
						SharePreferenceHelper.saveAppList(getActivity(), data);

						// Log.e(TAG, "onFinish:" + homeMenuDatas.size());
						homeMenuListAdapter.notifyDataSetChanged();
					}

					@Override
					public void onFailed(String Message) {
						// TODO Auto-generated method stub
						// Log.e(TAG, "onFailed:" + Message);
						homeMenuDatas.clear();
						// homeMenuDatas.addAll(homeMenuDatas1);
						homeMenuListAdapter.notifyDataSetChanged();
					}
				});
	}

	private void initIsShow() {
		homeMenuDatas.clear();
		for (int i = 0; i < AllMenuDatas.size(); i++) {
			EmployeeRightsEntity employeeRightsEntity = AllMenuDatas.get(i);
			String clientCode = employeeRightsEntity.getClientCode();
			SharedPreferences sp = getActivity().getSharedPreferences(
					clientCode, 0);
			// Log.e("HomeAppFragment", clientCode);
			boolean isshow = sp.getBoolean("isshow", true);
			// Log.e("HomeAppFragment", "isshow ="+isshow);
			if (isshow) {
				homeMenuDatas.add(employeeRightsEntity);
			}
		}
	}

	public void loginSuccess(boolean netFlag) {

		if (getActivity() == null) {
			return;
		}
		// autoscrollDatas.clear();
		// autoscrollDatas.add(weatherResp);
		//
		// int size = autoscrollDatas.size();
		// if (size > 1) {
		// size--;
		// } else {
		// size = 1;
		// // autoScrollViewPager.setCurrentItem(0);
		// }
		// autoScrollViewPager.setScrollDurationFactor(size);
		//
		// autoScrollViewPagerAdapter.notifyDataSetChanged();
		//
		// // 初始化圆点
		// initDot();
		prepareData(netFlag);
		Log.i(TAG, "Login success init home data success");
	}

	public void prepareData(boolean netFlag) {

		if (getActivity() != null) {

			// 获取首页缓存列表
			getCacheEmployee();

			// 网络存在并可用
			if (netFlag) {
				// 网路获取列表
				getEmployeeRight();
				// getAuth();
				long beginTime = DateUtils.getCurrentDate();
				long syntime = SharePreferenceHelper.getLongValue(
						getActivity(),
						SharePreferenceHelper.WeiTown_weather_time);
				// 登陆成功或后台进入前台（获取天气超过30分钟需要重新定位）
				if (beginTime - syntime >= 1800) {
					Log.i(TAG, "prepareData getLocation");
					// getLocation();
				}
			}
		}
	}

	// @Override
	// public void onActivityResult(int requestCode, int resultCode, Intent
	// data) {
	// if (data != null) {
	// if (requestCode == Constant.JumpManage_Code) {
	// if (resultCode == Constant.JumpManage_Code) {
	// // Log.e("HomeAppFragment", "OnActivityResult ");
	// prepareData(true);
	// // getEmployeeRight();
	// initIsShow();
	// }
	// }
	// }
	// super.onActivityResult(requestCode, resultCode, data);
	// }

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.tv_manage:
			startActivityForResult(new Intent(getActivity(),
					AppManngeActivity.class), Constant.JumpManage_Code);
			break;

		default:
			break;
		}
	}

	public boolean isJumpOutOfAppSharing() {
		return isJumpOutOfAppSharing;
	}

	public void setJumpOutOfAppSharing(boolean isJumpOutOfAppSharing) {
		this.isJumpOutOfAppSharing = isJumpOutOfAppSharing;
	}

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (data != null) {
			if (requestCode == Constant.JumpManage_Code) {
				if (resultCode == Constant.JumpManage_Code) {
					Log.e("HomeAppFragment", "OnActivityResult ");
					prepareData(true);
					// getEmployeeRight();
					initIsShow();
				}
			}
		}
		super.onActivityResult(requestCode, resultCode, data);
	}
}
